package com.github.xzb617.client.route.zuul.ribbon.support;

import com.github.xzb617.client.route.zuul.constant.RouteKey;
import com.github.xzb617.common.constants.Bool;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ServerHelper {

    /**
     * 是否在规则内
     * @param metadata
     * @param ruleValue
     * @return
     */
    private static boolean isRule(Map<String, String> metadata, String ruleValue) {
        String value = metadata.get(RouteKey.ROUTE_RULE_KEY);
        return value != null && value.equals(ruleValue);
    }

    /**
     * 过滤规则内实例
     * @param reachableServers 所有可达服务
     * @return
     */
    public static FilterResult filterRule(List<Server> reachableServers, String ruleValue) {
        List<Server> targetServers = new ArrayList<Server>();
        List<Server> othersServers = new ArrayList<>();
        for (Server reachableServer : reachableServers) {
            DiscoveryEnabledServer server = (DiscoveryEnabledServer) reachableServer;
            Map<String, String> metadata = server.getInstanceInfo().getMetadata();
            boolean isRuleServer = isRule(metadata, ruleValue);
            if (isRuleServer) {
                targetServers.add(server);
            } else {
                othersServers.add(server);
            }
        }
        // 有自定义规则式路由则返回实例集合，否则返回所有可达服务
        return new FilterResult(targetServers, othersServers);
    }


    /**
     * 是否为规则式路由的请求流量，且该流量在设置的比重范围内
     * @param attributes ribbon context attribute
     * @return
     */
    public static boolean isRuleRequestWithinWeight(Map<String, String> attributes) {
        boolean var01 = attributes.containsKey(RouteKey.ROUTE_RULE_KEY);
        if (var01) {
            String var02 = attributes.get(RouteKey.ROUTE_RULE_KEY + "-equal");
            return Bool.TRUE.equals(var02);
        }
        return false;
    }
}
